<template>
  <view class="container">
    <view class="form">
      <uni-forms ref="formRef" label-position="top" :model="formData" :rules="rules" label-width="100vw">
        <template v-for="item in options">
          <slot :name="`before${item.prop}`" :formData="formData" :option="item"></slot>
          <slot :name="item.prop" :formData="formData" :option="item">
            <uni-forms-item :key="item.prop" :label="item.label" :required="item.required" :rules="
                item.required
                  ? [
                      {
                        required: true,
                        errorMessage: '字段为必填项',
                      },
                    ]
                  : []
              " :name="item.prop">
              <uni-easyinput :style="{
                  border: 'none',
                }" v-if="item.type == 'input'" @change="changeInput(item, $event)" type="text"
                v-model="formData[item.prop]" :disabled="item.prop == 'sqr'"
                :placeholder="placeholders[item.type] + item.label" />
              <uni-combox :candidates="selectZyry" v-else-if="item.type == 'zyry'" v-model="formData[item.prop]"
                @change="changeZyry(item, $event)"></uni-combox>

              <!-- 其他安全措施 -->
              <uni-combox :candidates="qtaqcsItems" v-else-if="item.type == 'qtaqcs'"
                v-model="formData[item.prop]"></uni-combox>

              <!-- <rudon-multiSelector
              v-else-if="item.type == 'zyry'"
              welcome="请选择"
              :is_using_slot="false"
              :is_using_icon="true"
              :localdata="selectZyry"
              v-model="formData[item.prop]"
            ></rudon-multiSelector> -->
              <template v-else-if="item.type == 'glzyp'">
                <rudon-multiSelector welcome="请选择" :is_using_slot="false" :is_using_icon="true" :localdata="zypList"
                  v-model="formData[item.prop]"></rudon-multiSelector>
              </template>
              <template v-else-if="item.type == 'zsbh'">
                <rudon-multiSelector welcome="请选择" :is_using_slot="false" :is_using_icon="true"
                  :localdata="getZsSelect[item.prop]" v-model="formData[item.prop]"></rudon-multiSelector>
              </template>

              <rudon-multiSelector v-else-if="item.type == 'mselect'" welcome="请选择" :is_using_slot="false"
                :is_using_icon="true" :localdata="item.optionItems" v-model="formData[item.prop]"></rudon-multiSelector>
              <uni-combox :candidates="item.optionItems" v-else-if="item.type == 'combox'"
                v-model="formData[item.prop]"></uni-combox>
              <uni-combox v-else-if="item.type == 'userselect'" :names="form.reviewUserName"
                @change="onUserChange('reviewUser', $event)" :limit="1"></uni-combox>
              <uni-data-select style="border: none" v-else-if="item.type == 'select'" v-model="formData[item.prop]"
                :localdata="item.optionItems" @change="change(item.prop, $event)"
                :placeholder="placeholders[item.type] + item.label"></uni-data-select>
              <uni-datetime-picker v-else-if="
                  ['datetime', 'date', 'datetimerange', 'daterange'].includes(
                    item.type
                  )
                " :type="item.type" v-model="formData[item.prop]" @change="change(item.prop, $event, item.type)"
                :placeholder="placeholders[item.type] + item.label" :hide-second="true" />

              <!-- 自动计算结束时间组件 -->
              <view v-else-if="['newdatetimerange'].includes(item.type)">
                <uni-datetime-picker v-model="formData[item.prop][0]" placeholder="请选择开始时间" type="datetime"
                  :hide-second="true" @change="changeJobTime(item.prop, $event, item.type)"
                  :disabled="jobType == 2 && !formData.dhzyjb"></uni-datetime-picker>
                <uni-datetime-picker v-model="formData[item.prop][1]" type="datetime" :hide-second="true"
                  placeholder="自动带出结束时间" :disabled="jobType == 2 && !formData.dhzyjb"></uni-datetime-picker>
              </view>
              <uni-data-checkbox v-else-if="item.type == 'radio' || item.type == 'checkbox'"
                v-model="formData[item.prop]" :localdata="item.optionItems" :multiple="item.type == 'checkbox'"
                @change="change(item.prop, $event)"></uni-data-checkbox>
              <uploadFileVue v-else-if="item.type == 'file'" v-model="formData[item.prop]"></uploadFileVue>
            </uni-forms-item>
          </slot>
        </template>
      </uni-forms>
    </view>
    <button type="primary" class="submit" @click="submitForm">提 交</button>
  </view>
</template>

<script setup>
  import {
    ref,
    defineProps,
    defineEmits,
    watch,
    nextTick,
    computed
  } from "vue";
  import {
    router
  } from "@/router/index.js";
  import uploadFileVue from "@/components/uploadFile.vue";
  import {
    formatDate
  } from "@/utils/index.js";
  import {
    apis
  } from "@/api/zygl/zyp";

  const placeholders = {
    datetime: "请选择",
    date: "请选择",
    datetimerange: "请选择",
    daterange: "请选择",
    select: "请选择",
    input: "请输入",
    zyry: "请选择",
    qtaqcs: "请选择",
  };
  const emits = defineEmits(["onChange", "onSubmit"]);
  const props = defineProps({
    rules: {
      type: Object,
      default: () => ({}),
    },
    formOption: {
      type: Array,
      default: () => [],
    },
    zyryList: {
      type: Array,
      default: () => [],
    },
    zypList: {
      type: Array,
      default: () => [],
    },
    jobType: [String, Number],
  });

  const submitForm = async () => {
    const res = await getFormData();
    if (res) {
      formatTimes();
      emits("onSubmit", {
        ...keepData.value,
        ...formData.value
      });
      return {
        ...keepData.value,
        ...formData.value
      };
    } else {
      uni.showModal({
        title: "有必填项未填",
      });
      return false;
    }
  };
  const options = ref([]);
  const formData = ref({});
  const keepData = ref({});

  function setFormData(data = {}) {
    keepData.value = JSON.parse(JSON.stringify(data));
    formData.value = {
      ...data
    };
  }

  function setOptions(option) {
    if (option) {
      options.value = JSON.parse(JSON.stringify(option));
    } else {
      options.value = [];
    }
  }
  const formRef = ref();
  async function getFormData() {
    try {
      const res = await formRef.value.validate();
      return res;
    } catch (e) {
      return false;
    }
  }
  const workTime = ref({
    5: 360,
    3: 168,
    10: 24,
  });
  // 自动计算时间
  const workTimeFire = ref({
    "特级（8H）": 8,
    "一级（8H）": 8,
    "二级（72H）": 72,
  });
  const changeJobTime = (prop, value, type) => {
    nextTick(() => {
      if (prop == "jobDate" && props.jobType == 2) {
        let beginTime = getDateFromString(value);
        formData.value[prop][1] = formatDate(
          beginTime.setHours(
            beginTime.getHours() + workTimeFire.value[formData.value.dhzyjb]
          )
        );
      } else if (prop == "jobDate" && workTime.value[props.jobType]) {
        let beginTime = getDateFromString(value);
        formData.value[prop][1] = formatDate(
          beginTime.setHours(beginTime.getHours() + workTime.value[props.jobType])
        );
      }
    });
  };

  function getDateFromString(str) {
    var reg = /^(\d+)-(\d+)-(\d+) (\d+):(\d+)/;
    var s = str.match(reg);
    var result = "";
    if (s) {
      result = new Date(s[1], s[2] - 1, s[3], s[4], s[5]);
    }
    return result;
  }

  const change = (key, value) => {
    emits("onChange", {
      key,
      value,
    });
  };

  defineExpose({
    setFormData,
    setOptions,
    getFormData,
    submitForm,
  });
  const selectZyry = ref([]);
  const zyzsbh = ref({});

  const qtaqcsItems = ref([
    '安全帽','防静电工作服','劳保鞋','绝缘鞋(靴)','防护手套','绝缘焊接手套','绝缘手套','焊接面具','面罩','护目镜','防尘毒口罩','耳塞','安全带','四合一气体检测仪','照明用具','通讯设备','其他防护'
  ])

  watch(
    () => props.zyryList,
    () => {
      apis
        .getZyZsList({
          ids: props.zyryList
            .filter((ele) => ele.type == "out")
            .map((item) => item.id),
        })
        .then((res) => {
          zyzsbh.value = res.data;
        });
      selectZyry.value = props.zyryList.map((item) => item.label || item.name);
    }
  );

  const changeInput = (op, value) => {
    if (!op.hz || value.includes(op.hz)) {
      return;
    } else {
      formData.value[op.prop] = value + op.hz;
    }
  };
  const formatTimes = () => {
    options.value.forEach((item) => {
      if (item.type.includes("time")) {
        let value = formData.value[item.prop];
        if (item.type.includes("range")) {
          value = formData.value[item.prop] || [];
          let values = [];
          if (value.length == 0) return;
          value.forEach((ele, index) => {
            if (!ele || ele.length < 2) {
              return (values[index] = "");
            }
            if (ele.length < 12) {
              values[index] = ele + "00:00";
            } else {
              values[index] = ele;
            }
          });
          formData.value[item.prop] = values;
        } else {
          if (!value) return;
          formData.value[item.prop] = value.length < 12 ? value + "00:00" : value;
        }
      }
    });
  };
  const zyzsList = ref([]);

  //  text: ele.specialNumber + "-" + zypTypes[ele.jobType],
  //           value: ele.specialNumber,
  //           id: ele.id,
  //           ptw: ele.ptw,
  // 选择作业人员 自动带出票证号
  const changeZyry = (option, val) => {
    const zsOption = options.value.find(op => op.pProp === option.prop)
    if(!zsOption) {
      return
    }
    if(getZsSelect.value[zsOption.prop] && getZsSelect.value[zsOption.prop].length) {
      const codes = getZsSelect.value[zsOption.prop].map(ele => ele.value)
      if (formData.value[zsOption.prop] && formData.value[zsOption.prop].length) {
        const delIndex = []
          formData.value[zsOption.prop].forEach((ele,index) => {
          if(!codes.includes(ele)) {
            delIndex.push(index)
          }
        })
        delIndex.forEach(index => {
          formData.value[zsOption.prop].splice(index,1)
        })
      }
    }
 
    // if (option.bh) {
    //   const zsbh = props.zyryList.filter((item) => val.includes(item.name));
    //   let selectedList = [];
    //   zsbh.forEach((item) => {
    //     const list = zyzsbh.value[item.id];
    //     if (list && list.length) {
    //       list.forEach((ele) => {
    //         selectedList.push({
    //           text: item.name + "-" + ele.certificateName + "-" + ele.certificateCode,
    //           value: ele.certificateCode,
    //           id: ele.id,
    //         });
    //       });
    //     }
    //   });
    //   zyzsList.value = selectedList;
    // }
  };
  const getZsSelect = computed(() => {
    const mapSelect = {};
    if (options.value.length) {
      options.value.forEach((item) => {
        if (item.pProp && formData.value[item.pProp]) {
          const zsbh = props.zyryList.filter((user) =>
            formData.value[item.pProp].includes(user.name)
          );
          let selectedList = [];
          zsbh.forEach((it) => {
            const list = zyzsbh.value[it.id];

            if (list && list.length) {
              let codes = list.map(ele => {
                selectedList.push({
                  text: it.name +
                    "-" +
                    ele.certificateName +
                    "-" +
                    ele.certificateCode,
                  value: ele.certificateCode,
                  id: ele.id,
                });
                return ele.certificateCode
              })

              // list.forEach((ele) => {
              //   selectedList.push({
              //     text:
              //       item.name +
              //       "-" +
              //       ele.certificateName +
              //       "-" +
              //       ele.certificateCode,
              //     value: ele.certificateCode,
              //     id: ele.id,
              //   });
              // });
            }
          });
          mapSelect[item.prop] = selectedList;
        }
      });
    }
    return mapSelect;
  });

</script>

<style lang="scss" scoped>
  .page {
    background-color: #fff !important;
  }

  .is-input-border {
    border: none !important;
  }

  .container {
    background-color: #fff !important;
    padding-bottom: 12vw;

    .form {
      padding: 16px;
    }
  }

  .checklist-group {
    padding: 10px;
  }

  .submit {
    position: fixed;
    bottom: 0;
    height: 12vw;
    width: 100vw;
  }
</style>
